﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Controllers
{
	using System.Web.Mvc;
	using Falcon.Core.Domain;
	using Falcon.Core.Domain.Services;
	using Falcon.Core.Domain.Values;
	using Falcon.Core.Extensions;
	using Falcon.Core.Validation;

	public class PollController : DefaultController
	{
		public PollController(
			IPollService pollService,
			IPollChoiceService pollChoiceService,
			IPollTrackingService pollTrackingService)
		{
			this.PollService = pollService;
			this.PollChoiceService = pollChoiceService;
			this.PollTrackingService = pollTrackingService;
		}

		public IPollService PollService
		{
			get;
			private set;
		}

		public IPollChoiceService PollChoiceService
		{
			get; 
			private set;
		}

		public IPollTrackingService PollTrackingService
		{
			get;
			private set;
		}

		[AcceptVerbs(HttpVerbs.Post), Authorize]
		public ActionResult Vote(PollVote value)
		{
			try
			{
				var tracking = PollTrackingService.GetBy(new PollTrackingSpecification
				{
					PollId = value.PollId,
					UserId = Identity.Id
				});

				if (tracking != null)
				{
					return Error(Resources.Messages.PollAlreadyVoted);
				}

				var choice = PollChoiceService.GetById(value.ChoiceId);

				if (choice == null)
				{
					return Error(Resources.Messages.PollChoiceNotFound);
				}

				choice.Update();

				PollChoiceService.Update(choice);
				PollTrackingService.Insert(choice);
			}
			catch (ValidationException exception)
			{
				ModelState.CopyValidationExceptions(exception);
			}

			return Redirect(value.Redirect);
		}
	}
}